% $Id: BatchLoader.m 7 2009-01-27 12:46:40Z Jie.Bao $

classdef BatchLoader
%BathLoader class that iterates through all logs in a folder
%  Takes an input folder location such as 'data/subject1/' and an
%  ExperimentSetup object. Read the entire input directory and loads all
%  the files. Main functions needed are the constructor, Process(), and
%  WriteStatisticsFile(). Process creates velocity histograms and path
%  plots for each log. WriteStatisticsFile will output a csv file of all
%  the statistics for teh entire project.All this does is iterate through 
%  all logs on the directory and perform the same task. It saves time by
%  not having to manualy load every log file and analyze it

   properties
       FileNames;
       Directory;
       Length;
       Files = {};
       Experiment;
   end

   methods
       %CONSTRUCTOR
       %Needs the directory to open and teh
       %ExperimentSetup object. This object is used to find output paths as
       %well as a few other constants used throughout the experiment.
       function obj = BatchLoader(directory, experiment)
            obj.Experiment = experiment;
            obj.Directory = directory;
            files = dir(fullfile('', [obj.Directory, '*.csv'])); 
            %files = dir(fullfile('', [obj.Directory, '*.txt']));
            obj.Length = length(files);
            
            new_files = struct('name',{});
            i = 1;
            for j=1:obj.Length
                current_file = files(j).name;
                % parse only non-event log files with 'self' in the file
                % name
                if isempty(strfind(current_file, '[EVENT]')) && ...
                        ~isempty(strfind(current_file, 'self'))
                    disp(current_file);
                    new_files(i).name = files(j).name;
                    i = i+1;
                end        
            end
            obj.FileNames = new_files;
            obj.Length = length(obj.FileNames);
            
            item_list = [];
            file_list = {};
            for j=1:obj.Length
                file = FileLoader(obj.Directory, obj.FileNames(j).name, obj.Experiment);
                file.EasyPlot()
                pause
                file_list{end+1} = file;
                item_list(end+1) = str2double(file.Item);
            end

            % sort files by item number
            [dummy order] = sort(item_list);
            for i = 1:length(order)
                obj.Files{i} = file_list{order(i)};
            end
       end
       
       %MAIN FUNCTIONS
       
       %Process goes through every log file. Outputs a historgram of the
       %velocities. THen it proceeds to save this file according to a set
       %naming method. Finally it plots the floor plan, and the path on top
       %of that. It also plots stops on top of that and saves the file
       function obj = Process(obj)
            for j=1:obj.Length
                j
                obj.Files{j} = obj.Files{j}.AnalyzeVelocities();
                obj.Files{j}.AddMeta();
                obj.Files{j}.Save('histo-gram');
                clf
                hold off
                obj.Files{j} = obj.Files{j}.EasyPlot();
                obj.Files{j}.AddMeta();
                axis image
                obj.Files{j}.Save('paths');                
                hold off
                clf
            end
       end
       
       
       
       %this is ally ou need to run. It creates all the graphs and
       %statistics files.
       function this = Analyze(this)
           %this = this.Split();
           %this.Process();
           this.WriteStatisticsFile();
           %this.WriteAreaCoveredFile();
           %this.WriteStopsFile();
           %this.WriteRegionFile();
       end
       
       
       %creates a .csv file. Outputs the variable headings on lien 1.
       %creates 1 line for each log file that includes all the information
       %from the file and many of the available statistics.
       function WriteStatisticsFile(this)
           %new file every time version
           %out = fopen([this.Experiment.OutPutDirectory '/'...
           %             num2str(this.Files{1}.Subject) ...
           %             'statistics.csv'], 'w');
           
           %append version 
           out = fopen([this.Experiment.OutPutDirectory '/'...
                        'statistics.csv'], 'a');
                    
                    
           %h = this.Files{1}.GetTableHeadings();
           h = 'subject,item,path length,stop number,stop duration\n';
           %fprintf(out, h);
           for j = 1:this.Length
               j
               %stat = this.Files{j}.GetStatisticsCSV();
               stat = this.Files{j}.GetMyStatistics();
               fprintf(out, stat);
           end
           fclose(out);
       end
       
       %writes a .csv file that for each log file contains all teh regions
       %and the time/distance theyw ere discovered at
       function WriteAreaCoveredFile(this)
           %new file every time version 
           %out = fopen([this.Experiment.OutPutDirectory '/' ...
           %             num2str(this.Files{1}.Subject) ...
           %             'areaCoveredStatistics.csv'], 'w');
           
           % append version
           out = fopen([this.Experiment.OutPutDirectory '/' ...
                            'areaCoveredStatistics.csv'], 'a');
           
           h = this.Files{1}.GetAreaCoveredTableHeadings();
           fprintf(out, h);
           for j = 1:this.Length
               j
               stat = this.Files{j}.GetAreaCoveredStatistics();
               fprintf(out, stat);
           end
           fclose(out);
       end
       
       %writes a .csv file that has every stop from the entire log. With
       %each stop it includes the location, duration, sweep and range of
       %rotation
       function WriteStopsFile(this)
           %new file every time version
           %out = fopen([this.Experiment.OutPutDirectory '/' ...
           %             num2str(this.Files{1}.Subject) ...
           %             'stopsStatistics.csv'], 'w');
           
           % append version
           out = fopen([this.Experiment.OutPutDirectory '/' ...
                        'stopsStatistics.csv'], 'a');
                    
           h = this.Files{1}.GetStopStatisticsHeadings();
           fprintf(out, h);
           for j=1:this.Length
               j
               stat = this.Files{j}.GetStopStatistics();
               fprintf(out,stat);
           end
           fclose(out);
       end
       
       
       %write a .csv file that has for each log a list of the regions. From
       %those regions ti has a duration spent in this region
       function WriteRegionFile(this)
           %new file every time version
           %out = fopen([this.Experiment.OutPutDirectory '/' ...
           %             num2str(this.Files{1}.Subject) ...
           %             'regionStatistics.csv'], 'w');
            
           %append version         
           out = fopen([this.Experiment.OutPutDirectory '/' ...
                        'regionStatistics.csv'], 'a');
           
                    
                    
           h = this.Files{1}.GetRegionTableHeadings();
           fprintf(out, h);
           for j=1:this.Length
               j
               stat = this.Files{j}.GetRegionStatistics();
               fprintf(out,stat{1});
           end
           fclose(out);
       end
         
       %looks through all of the log files included. Searches for all that
       %are exploration. Once it finds all exploration it finds the first
       %search with, and search with out exploration for that same subject.
       %It then determiens the length of those and splits the exploration
       %according to that. These new logs are output ina  seperate splits
       %directory in the original data area. They are also kept around to
       %be graphed later.
       function this = Split(this)
            %find all the exploration files
            for j=1:this.Length
                %trial is 0, and the condition has an E at the end
                if strcmp(this.Files{j}.Trial,'0') && ...
                    (  this.Files{j}.Condition(length(this.Files{j}.Condition)) == 'E' || ...
                    this.Files{j}.Condition(length(this.Files{j}.Condition)) == 'E' )
                    % find the associated 1st trials.
                    for i=1:this.Length
                        % if it is the same subject and trial 1
                        if strcmp(this.Files{i}.Subject, this.Files{j}.Subject) && ...
                           strcmp(this.Files{i}.Trial, '1') && ...
                           (this.Files{i}.Condition(1) ~= 'I' && ...
                            this.Files{i}.Condition(1) ~= 'i' )
                            %value needed to know if the cut is from exp or
                            %without exploration
                            with = 1;
                            if this.Files{i}.Condition(5) == 'E' || this.Files{i}.Condition(5) == 'e'
                                with = 2;
                            end
                            new = this.Files{j}.Split(this.Files{i}.Length, with);
                            
                            %save the value for the statistics and file
                            %outputs.
                            this.Files{length(this.Files)+1} = new;
                            this.Length = this.Length +1;
                            
                            %we output the graphs of both the cut
                            %exploration and the trial that it is for
                            
                            this.Files{i}.EasyPlot();
                            this.Files{i}.AddMeta();
                            axis image;
                            this.Files{i}.Save('splits');
                            hold off;
                            clf;
                            
                            new.EasyPlot();
                            new.AddMeta();
                            axis image
                            new.Save('splits');
                            hold off
                            clf;
                        end
                    end
                end
            end
        end
       
       
       %ADDITIONAL LESS IMPORTANT AND "PRIVATE" FUNCTIONS       
       function obj = Plot(obj)
           for j=1:obj.Length
               obj.Files{j}.EasyPlot();
           end
       end
       
       function this = Headings(this)
           for j=1:this.Length
              this.Files{j}.Floor.Plot;
              this.Files{j}.PathA.Plot(1,0,0);
              axis image
              this.Files{j}.TurnA.Plot(1)
              pause(2);
              clf
           end
       end 
       
       function stat = GetStatisticsByTrial(obj)
            stats=[];
            for j=1:obj.Length
                j
                stats(j,1) = obj.Files{j}.GetTrial();                
                [td, av, dot, mv] = obj.Files{j}.GetStatistics();
                stats(j,2) = td;
                stats(j,3) = av;
                stats(j,4) = dot;
                stats(j,5) = mv;
            end
            [t,i] = sort(stats(:,1));
            stat = stats(i,:);
       end
       
       function stat = GetAnglesByTrial(this)
           stat = {};
           for j=1:this.Length
               stat{j} = this.Files{j}.GetAngles();
               %this.Files{j}.AnalyzePath();
           end
       end
       
       function stat = GetPathAnalysisByTrial(this)
           stat ={};
           for j=1:this.Length
               line = [this.Files{j}.GetTrial this.Files{j}.AnalyzePath()];
               stat{j} = line;
           end
       end
   end
end 


   
   